import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/team/soccer/zq_team_schedule_logic.dart';
import 'package:ball_lion/entity/team/zq_team_schedule_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class SoccerTeamScheduleView extends StatefulWidget {
  const SoccerTeamScheduleView({super.key, required this.teamId});
  final int teamId;

  @override
  State<SoccerTeamScheduleView> createState() => _SoccerTeamScheduleViewState();
}

class _SoccerTeamScheduleViewState extends State<SoccerTeamScheduleView>
    with AutomaticKeepAliveClientMixin {
  late final SoccerTeamScheduleLogic logic =
      Get.put(SoccerTeamScheduleLogic(), tag: widget.teamId.toString());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<SoccerTeamScheduleLogic>(
        initState: (state) async {
          await logic.requestYears(widget.teamId);
          await logic.requestData(widget.teamId);
          Future.delayed(const Duration(milliseconds: 500))
              .then((value) => logic.initObserver());
        },
        tag: widget.teamId.toString(),
        builder: (controller) {
          return LoadingWidget<bool>(
            isLoading: controller.years == null,
            data: controller.years?.length == 0,
            child: () => Container(
              color: Colours.N1,
              child: Column(
                children: [
                  _pageChoice(),
                  Expanded(
                      child: LoadingWidget<bool>(
                    isLoading: controller.matchGroup == null,
                    data: controller.matchGroup?.length == 0,
                    child: () => MediaQuery.removePadding(
                      context: context,
                      removeTop: true,
                      child: controller.years?[controller.yearIndex].count == 0
                          ? const NoDataWidget()
                          : ListView(
                              controller: controller.scrollC,
                              physics: const ClampingScrollPhysics(),
                              children: List.generate(
                                  controller.matchGroup?.length ?? 0,
                                  (index) => _listItem(index).paddingOnly(
                                      bottom: (controller.matchGroup?.length ==
                                              index + 1)
                                          ? 50
                                          : 0))),
                    ),
                  )),
                ],
              ),
            ),
          );
        });
  }

  Widget _pageChoice() {
    return Container(
      height: 40,
      color: Colours.white,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 12, right: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () async {
              await logic.showDatePicker();
              await logic.requestData(widget.teamId);
              await Future.delayed(const Duration(microseconds: 500)).then(
                  (value) => logic.observerController.jumpTo(
                      index: logic.years?[logic.yearIndex].year.toString() ==
                              DateTime.now().formatedString('yyyy')
                          ? logic.data?.matchGroup?.indexWhere((element) =>
                                  element.title ==
                                  DateTime.now().formatedString('yyyy-MM')) ??
                              0
                          : (logic.data?.matchGroup?.length ?? 1) - 1));
            },
            child: Container(
              height: 24,
              width: 60,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 6, right: 2),
              margin: const EdgeInsets.only(right: 6),
              decoration: BoxDecoration(
                  color: Colours.greyF2F3F7,
                  borderRadius: BorderRadius.circular(12)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsText("${logic.years?[logic.yearIndex].year ?? ''}",
                        needCenter: true, fontSize: 12),
                    const SizedBox(width: 2),
                    Padding(
                      padding: const EdgeInsets.only(top: 1),
                      child: Image.asset(
                        Utils.getImgPath('year_down_arrow.png'),
                        width: 8,
                        height: 6,
                      ),
                    )
                  ]),
            ),
          ),
          Container(width: 5),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                    logic.data?.leagueArray?.length ?? 0,
                    (childIndex) => Flexible(
                          flex: 1,
                          child: GestureDetector(
                            onTap: () async {
                              logic.getType(childIndex);
                            },
                            child: Container(
                              height: 24,
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 16),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  color: logic.typeIndex == childIndex
                                      ? Colours.B6
                                      : Colours.white),
                              child: QsText(
                                  logic.data?.leagueArray?[childIndex]
                                          .leagueName ??
                                      "",
                                  color: logic.typeIndex == childIndex
                                      ? Colours.white
                                      : Colours.N9,
                                  needCenter: true,
                                  fontSize: 14),
                            ),
                          ),
                        )),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _listItem(itemIndex) {
    return Container(
      //margin: const EdgeInsets.only(top: 0, left: 8, right: 8),
      decoration: BoxDecoration(color: Colours.white),
      // child: Padding(
      //   //padding: const EdgeInsets.only(bottom: 8),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              width: Get.width,
              height: 30,
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(left: 10),
              decoration: const BoxDecoration(color: Color(0xFFF2F3F7)),
              child: QsText(
                "${(logic.matchGroup?[itemIndex].title ?? "").split('-').join('年')}月",
                fontSize: 14,
                color: Colours.N9,
              )),
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: logic.matchGroup?[itemIndex].matchArray?.length ?? 0,
            separatorBuilder: (_, __) => const Divider(
              height: 0.5,
              color: Colours.N3,
            ),
            itemBuilder: (context, index) =>
                _childItem(logic.matchGroup?[itemIndex].matchArray?[index]),
          )
        ],
      ),
      //,
    );
  }

  Widget _childItem(MatchArray? entity) {
    return GestureDetector(
      // onTap: () =>
      //     Get.toNamed(Routes.zqMatchDetail, arguments: entity?.qxbMatchId),
      child: Stack(
        alignment: Alignment.center,
        children: [
          SizedBox(
              height: 80,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 2),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          QsText(
                              DateTime.parse(entity?.matchTime ?? '')
                                      .formatedString("MM-dd HH:mm") ??
                                  "-",
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                              color: Colours.N7),
                          QsText(
                              (entity?.leagueName != null &&
                                          entity?.leagueName != ''
                                      ? "${entity!.leagueName}\u2000"
                                      : "") +
                                  (entity?.groupCn != null &&
                                          entity?.groupCn != ''
                                      ? entity!.groupCn!
                                      : ""),
                              color: Colours.N7,
                              fontSize: 12),
                          Container(
                            width: 60,
                            alignment: logic.formScore(2, entity) == ""
                                ? null
                                : Alignment.centerRight,
                            child: logic.formScore(2, entity) == ""
                                ? null
                                : QsText(
                                    logic.formScore(2, entity),
                                    fontSize: 10,
                                    color: Colours.N7,
                                  ),
                          )
                        ],
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerRight,
                            child: QsText(entity?.homeName ?? "-",
                                fontSize: 13,
                                color: Colours.N9,
                                maxLines: 2,
                                textAlign: TextAlign.end),
                          ),
                        ),
                        SizedBox(
                          width: 50,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              QsText(logic.formScore(1, entity),
                                  fontSize: 20,
                                  fontFamily: 'D-DIN-PRO',
                                  fontWeight: FontWeight.w800,
                                  color: Colours.N9),
                            ],
                          ),
                        ),
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerLeft,
                            child: QsText(entity?.guestName ?? '-',
                                fontSize: 13,
                                color: Colours.N9,
                                maxLines: 2,
                                textAlign: TextAlign.start),
                          ),
                        ),
                      ],
                    ),
                  ])),
          if (entity?.isWin != null)
            Positioned(
                right: 12,
                bottom: 18,
                child: Container(
                    height: 14,
                    width: 14,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                            bottomLeft: Radius.circular(2),
                            topRight: Radius.circular(2)),
                        color: [
                          Colours.C1,
                          Colours.R1,
                          Colours.R1
                        ][entity!.isWin!]),
                    child: QsText(["负", "胜", "平"][entity.isWin!],
                        fontSize: 10,
                        color: [
                          Colours.C6,
                          Colours.R6,
                          Colours.R6
                        ][entity.isWin!])))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
